<template>
  <div class="users-container">
    <div class="table-operations">
      <a-space>
        <a-button type="primary" @click="showCreateModal">
          <plus-outlined /> 新建用户
        </a-button>
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索用户名/邮箱"
          style="width: 200px"
          @search="handleSearch"
        />
      </a-space>
    </div>

    <a-table
      :columns="columns"
      :data-source="users"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #status="{ text }">
        <a-tag :color="text === 1 ? 'success' : 'error'">
          {{ text === 1 ? '正常' : '禁用' }}
        </a-tag>
      </template>

      <template #action="{ record }">
        <a-space>
          <a @click="showEditModal(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="handleResetPassword(record)">重置密码</a>
          <a-divider type="vertical" />
          <a-popconfirm
            title="确定要删除此用户吗��"
            @confirm="handleDelete(record)"
          >
            <a class="danger">删除</a>
          </a-popconfirm>
        </a-space>
      </template>
    </a-table>

    <!-- 用户表单弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="modalVisible"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="用户名" name="username">
          <a-input
            v-model:value="formState.username"
            :disabled="!!formState.id"
            placeholder="请输入用户名"
          />
        </a-form-item>

        <a-form-item
          v-if="!formState.id"
          label="密码"
          name="password"
        >
          <a-input-password
            v-model:value="formState.password"
            placeholder="请输入密码"
          />
        </a-form-item>

        <a-form-item label="邮箱" name="email">
          <a-input
            v-model:value="formState.email"
            placeholder="请输入邮箱"
          />
        </a-form-item>

        <a-form-item label="状态" name="status">
          <a-switch
            v-model:checked="formState.status"
            :checked-value="1"
            :unchecked-value="0"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import {
  getUsers,
  createUser,
  updateUser,
  deleteUser,
  resetPassword
} from '@/api/user'

const searchKeyword = ref('')
const loading = ref(false)
const users = ref([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: total => `共 ${total} 条`
})

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'username'
  },
  {
    title: '邮箱',
    dataIndex: 'email'
  },
  {
    title: '状态',
    dataIndex: 'status',
    slots: { customRender: 'status' }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    slots: { customRender: 'action' }
  }
]

// 表单相关
const formRef = ref()
const modalVisible = ref(false)
const modalLoading = ref(false)
const modalTitle = ref('')
const formState = reactive({
  id: '',
  username: '',
  password: '',
  email: '',
  status: 1
})

const rules = {
  username: [
    { required: true, message: '请输入用户名' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符' }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { min: 6, max: 20, message: '密码长度为6-20个字符' }
  ],
  email: [
    { required: true, message: '请输入邮箱' },
    { type: 'email', message: '请输入正确的邮箱格式' }
  ]
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const { data } = await getUsers({
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchKeyword.value
    })
    users.value = data.list
    pagination.total = data.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchUsers()
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  fetchUsers()
}

// 显示创建用户弹窗
const showCreateModal = () => {
  modalTitle.value = '新建用户'
  Object.assign(formState, {
    id: '',
    username: '',
    password: '',
    email: '',
    status: 1
  })
  modalVisible.value = true
}

// 显示编辑用户弹窗
const showEditModal = (record) => {
  modalTitle.value = '编辑用户'
  Object.assign(formState, {
    id: record.id,
    username: record.username,
    email: record.email,
    status: record.status
  })
  modalVisible.value = true
}

// 弹窗确认
const handleModalOk = () => {
  formRef.value.validate().then(async () => {
    modalLoading.value = true
    try {
      if (formState.id) {
        await updateUser(formState.id, formState)
        message.success('更新成功')
      } else {
        await createUser(formState)
        message.success('创建成功')
      }
      modalVisible.value = false
      fetchUsers()
    } catch (error) {
      console.error('操作失败:', error)
    } finally {
      modalLoading.value = false
    }
  })
}

// 弹窗取消
const handleModalCancel = () => {
  modalVisible.value = false
  formRef.value.resetFields()
}

// 删除用户
const handleDelete = async (record) => {
  try {
    await deleteUser(record.id)
    message.success('删除成功')
    if (users.value.length === 1 && pagination.current > 1) {
      pagination.current--
    }
    fetchUsers()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 重置密码
const handleResetPassword = async (record) => {
  try {
    await resetPassword(record.id)
    message.success('密码重置成功')
  } catch (error) {
    console.error('重置密码失败:', error)
  }
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.users-container {
  padding: 24px;
  background: #fff;
}

.table-operations {
  margin-bottom: 16px;
}

.danger {
  color: #ff4d4f;
}

.danger:hover {
  color: #ff7875;
}
</style> 